﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using _9jCardRegisterCollection.Utils;
using AntdUI;
using CardRegisterCollection.Model;

namespace _9jCardRegisterCollection.Views
{
    public partial class UserRoleAuth : UserControl
    {
        private Window window;
        public UserRoleAuth(Window window, string userId)
        {
            this.window = window;
            _userId = userId;
            InitializeComponent();

            InitData();
        }


        private string _userId;

        private readonly CardRegisterCollection.BLL.Role _roleBll = new CardRegisterCollection.BLL.Role();
        private readonly CardRegisterCollection.BLL.UserRole _userRoleBll = new CardRegisterCollection.BLL.UserRole();


        private void InitData()
        {
            var roles = _roleBll.GetList($" CreatedBy in (select UserName from [user] where UnitId = '{CurrentLoginInfo.UserInfo.UnitId}')");
            foreach (var role in roles)
            {
                cmbRoles.Items.Add(new SelectItem(1)
                {
                    Tag = role.ID,
                    Text = role.name
                });
            }

            var userRoles = _userRoleBll.GetListByUserId(_userId);
            if (userRoles != null && userRoles.Count > 0)
            {
                var roleNames = userRoles.Select(_ => _.RoleName).ToList();
                lblUserRoles.Text = "已授权角色：" + string.Join(",", roleNames);
            }
        }

        private void butAuth_Click(object sender, EventArgs e)
        {
            if (!Validation.CheckEmpty(window, this.cmbRoles, "请选择角色名称"))
            {
                return;
            }

            _userRoleBll.Delete(_userId);
            var userRole = new UserRole()
            {
                ID = Guid.NewGuid().ToString(),
                UserId = _userId,
                RoleId = cmbRoles.SelectedValue?.ToString(),
                CreatedAt = DateTime.Now,
                CreatedBy = CurrentLoginInfo.UserInfo.UserName
            };
            _userRoleBll.Add(userRole);
            this.Dispose();
        }

        private void butCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}
